<template>
  <view
    class="comm-input"
    :class="{
      'comm-input-disabled': disabled,
    }"
    :style="[globalStyle]"
  >
    <input
      v-model="valueAsync"
      :placeholder="placeholder"
      placeholder-class="comm-input-placeholder"
      class="comm-input-field"
      :type="type"
      :disabled="disabled"
      :maxlength="maxlength"
      :focus="focus"
      @input="$emit('input', $event.target.value)"
      @focus="$emit('focus')"
      @blur="$emit('blur')"
      @change="$emit('change', $event)"
    />

    <view
      v-if="suffix"
      class="comm-input-suffix"
      >{{ suffix }}</view
    >
    <view
      v-if="clearable && valueAsync !== ''"
      @click="clear"
      class="iconfont icon-close comm-input-clear"
    ></view>
  </view>
</template>

<script>
  export default {
    props: {
      value: {
        type: String,
        default: "",
      },
      placeholder: {
        type: String,
        default: "",
      },
      type: {
        type: String,
        default: "text",
      },
      disabled: {
        type: Boolean,
        default: false,
      },
      maxlength: {
        type: Number,
        default: 140,
      },
      focus: {
        type: Boolean,
        default: false,
      },
      clearable: {
        type: Boolean,
        default: false,
      },

      suffix: {
        type: String,
        default: "",
      },
    },

    data() {
      return {
        valueAsync: "",
      };
    },

    watch: {
      value(val) {
        this.valueAsync = val;
      },

      valueAsync(val) {
        this.$emit("input", val);
      },
    },

    created() {
      this.valueAsync = this.value;
    },

    mounted() {
      this.$nextTick(() => {
        this.$emit("input", this.valueAsync);
      });
    },

    methods: {
      clear() {
        this.valueAsync = "";
      },
    },
  };
</script>

<style lang="scss" scoped>
  .comm-input {
    display: flex;
    align-items: center;
    position: relative;
    border: 1px solid #e5e5e5;
    padding: 10rpx 15rpx;
    border-radius: 10rpx;

    .comm-input-field {
      flex: 1;
      padding: 0;
      border: none;
      outline: none;
      font-size: 28rpx;
      line-height: 50rpx;
      color: #333;
    }
    .comm-input-clear {
      margin-left: 15rpx;
      width: 28rpx;
      height: 28rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #cccccc;
      font-size: 22rpx;
      color: #fff;
      border-radius: 50%;
    }

    .comm-input-suffix {
      margin-left: 15rpx;
      font-size: 24rpx;
      line-height: 28rpx;
      color: $uni-extra-color;
    }
  }

  .comm-input-disabled {
    background-color: #f5f5f5;
  }

  ::v-deep .comm-input-placeholder {
    color: #999;
  }
</style>
